package com.example.wangandroid.activity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.view.View;
import android.widget.ArrayAdapter;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.example.activity.BaseActivity;
import com.example.wangandroid.adapter.VideoMp3Adapter;
import com.example.wangandroid.databinding.ActivityVideoBinding;
import com.kongzue.dialogx.dialogs.TipDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;

import org.fmod.FMOD;

import java.io.File;
import java.util.List;
import java.util.Objects;

@Route(path = "/app/VideoActivity")
public class VideoActivity extends BaseActivity {

    static {
        System.loadLibrary("native-lib");
    }
    private MediaPlayer mediaPlayer;
    private String fileName = "audio.mp3";
    private int selectTV=1;
    private final static String[] startArray = {"原声","萝莉声", "男声", "小黄人", "空灵声", "女空灵声"};
    private ActivityVideoBinding binding;
    private VideoMp3Adapter videoMp3Adapter;
    private TextToSpeech textToSpeech=null;

    public static int MODE_NORMAL = 0; // 正常
    public static int MODE_LUOLI = 1; // 萝莉
    public static int MODE_DASHU = 2 ;// 大叔
    public static int MODE_JINGSONG = 3; // 惊悚
    public static int MODE_GAOGUAI = 4; // 搞怪
    public static int MODE_KONGLING = 5; // 空灵

    // private native String stringFromJNI();
    private native String stringFromJNI();
    // private native void voiceChangeNative(int mode, String path);
    private native void voiceChangeNative(int mode, String path);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityVideoBinding.inflate(getLayoutInflater());
        FMOD.init(this);
        setContentView(binding.getRoot());
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item,startArray);
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        binding.sp.setAdapter(arrayAdapter);
        mediaPlayer = new MediaPlayer();
        binding.btPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 VideoToFile();
                }
        });
        binding.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        File localf = new File(getExternalFilesDir(null).toURI());
        List<File> data = List.of(Objects.requireNonNull(localf.listFiles()));
        videoMp3Adapter = new VideoMp3Adapter(this, data);
        binding.recy.setAdapter(videoMp3Adapter);
    }


    private String path="";
    private void VideoToFile(){

        WaitDialog.show("正在转化语音...");
        textToSpeech = new TextToSpeech(VideoActivity.this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int i) {
                int position = binding.sp.getSelectedItemPosition();
                String text = binding.edInput.getText().toString();
                if(text.equals("")){
                    text = "你都没输入文字，想要我说什么?";
                }
                generateAudio(text);
                textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
                        @Override
                        public void onStart(String s) {

                        }

                        @Override
                        public void onDone(String s) {
                            updatefilelist();
                            if(!path.equals("")){

                                voiceChangeNative(position,path);
                            }
                        }

                        @Override
                        public void onError(String s) {
                            TipDialog.show("转化失败"+s);
                        }
                    });
            }
        });
    }

    // 给native调用的   方法签名： (Ljava/lang/String;)V
    void playerEnd(String nativeMessageContent) {
        TipDialog.show(nativeMessageContent,WaitDialog.TYPE.SUCCESS);
    }
    public  void updatefilelist(){
        File localf = new File(getExternalFilesDir(null).toURI());
        List<File> data = List.of(Objects.requireNonNull(localf.listFiles()));
        videoMp3Adapter.setdata(data);
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                videoMp3Adapter.notifyDataSetChanged();
            }
        });

    }

    @Override
    protected void onDestroy() {
        shutSpeekText();
        FMOD.close();
        super.onDestroy();
    }
    private void generateAudio(String text) {
        Bundle params = new Bundle();
        params.putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, text);
        String childString = System.currentTimeMillis()+fileName;
        File  f = new File(getExternalFilesDir(null), childString);
        textToSpeech.synthesizeToFile(text, params,
              f, f.getPath());
        path = f.getPath();

    }

    private void shutSpeekText(){
        if(textToSpeech==null)
            return;
        textToSpeech.stop();
        textToSpeech.shutdown();
        textToSpeech=null;
    }
}
